var DEBUG=false;
var HW_DATA_CONTROL = "HW_DATA_CONTROL";
var HW_LINK = "HW_LINK";
var HW_LINK_MOUSE_OVER = "HW_LINK_MOUSE_OVER";
var HW_LINK_MOUSE_OUT = "HW_LINK_MOUSE_OUT";
var g_readonly = false;
var g_cid;

function buildReport2(rt,sr,cid) {
//	g_readonly = true;
	buildDevice(rt, sr.device);
	buildScripts(sr.scripts);
	buildStyles(sr.styles);
	buildLayout(rt, sr.layout);
	g_cid = cid;
}

function buildReport(rt,sr) {
	//g_readonly = false;
	buildScripts(sr.selectSingleNode("scripts"));
	buildStyles(sr.selectSingleNode("styles"));
	buildLayout(rt, sr.selectSingleNode("layout"));
}

//* build the report layout according to the xml content received from the server */
function buildLayout(root, data) {
	if (g_readonly == false)
		g_oEditorContainer = new HWEditor();
	var tbl = document.createElement("TABLE");
	processLayout(data, tbl);
//	WinManager.open("result.html").text = data.xml;
//	WinManager.open("result.html").text = tbl.outerHTML;
	root.appendChild(tbl);
}

//* process the layout element in the report xml data */
function processLayout(data, tbl) {
	tbl.border=0;
	tbl.style.borderCollapse="collapse";
	tbl.style.tableLayout="fixed";
	tbl.style.margin="0 0 0 0";
	tbl.style.padding="0 0 0 0"
	tbl.cellPadding=0;
	tbl.cellSpacing=0;
	
	processCSS(tbl, data);
	processAttributes(tbl, data);

	//create columns of the layout table
	var gc = document.createElement("COLGROUP");
	tbl.appendChild(gc);
	var col;
	var lstCols = Common.getJSONArray(data.cols.col);
	var w = 0;
	for (var i = 0; i < lstCols.length; i++) {
		col = lstCols[i];
		var hc = document.createElement("COL");
		hc.style.width = col["@attributes"].width;
		w+= parseInt(hc.style.width);
		gc.appendChild(hc);
	}
	
	tbl.width=w;

	//create rows of the layout table
	var hr, r, lstRow = Common.getJSONArray(data.rows.row);
	var hc, lstCell;
	for (var i = 0; i < lstRow.length; i++) {
		r= lstRow[i];
		hr = tbl.insertRow(-1);
		hr.style.height = r["@attributes"].height;
		lstCell = Common.getJSONArray(r.cell);
		
		for (var j = 0; j < lstCell.length; j++) {
			c= lstCell[j];
			hc = hr.insertCell(-1);
			processCell(c, hc);
		}
	}
}

//* process the cell element in the report xml data */
function processCell(xmlCell,htmCell) {
	if (!xmlCell["@attributes"]) return;
	processCSS(htmCell, xmlCell);
	processAttributes(htmCell, xmlCell);
	var rowspan = xmlCell["@attributes"].rowspan;
	var colspan = xmlCell["@attributes"].colspan;
	if (null != rowspan)
		htmCell.rowSpan = rowspan;
	if (null != colspan)
		htmCell.colSpan = colspan;
	var data = xmlCell.table;
	if (null != data) {
		htmCell.vAlign = "top";
		htmCell.align = "left";
		var tbl = document.createElement("TABLE");
		processTable(tbl, data);
		htmCell.appendChild(tbl);
	} else if ((data = xmlCell.image)!=null) {
		htmCell.vAlign="top";
		htmCell.align="left";
		processImage(htmCell, data);
	} else {
		htmCell.vAlign="middle";
		htmCell.align="center";
		if (xmlCell["#text"])
			$(htmCell).append(xmlCell["#text"]);
	}
	
	//set editor object
	var lst = Common.getJSONArray(xmlCell.d);
	if (lst.length>0) {
		htmCell[HW_DATA_CONTROL] = xmlCell;
//		htmCell.setAttribute(HW_DATA_CONTROL, xmlCell);
		if (g_readonly == "false" || g_readonly == false ) {
			for (var i = 0; i < lst.length; i++) {
				if (lst[i]["@attributes"] && lst[i]["@attributes"].id)
					g_oEditorContainer.add(lst[i]["@attributes"].id, htmCell, lst[i]);
			}
		}
		updateHTMLCell(htmCell);
	}
	
	//set link object
	var link = xmlCell["@attributes"].link;
	processLink(link, htmCell);
}

/*  */
function processTable(tbl, data) {
	tbl.style.borderCollapse="collapse";
	tbl.style.tableLayout="fixed";
	tbl.cellPadding=0;
	tbl.cellSpacing=0;
	
	processCSS(tbl, data);
	processAttributes(tbl, data);
	tbl.style.height = data["@attributes"].height;
	tbl.style.width = data["@attributes"].width;

	//create columns of the layout table
	var gc = document.createElement("COLGROUP");
	tbl.appendChild(gc);
	var al;
	var hc,col,lstCols = Common.getJSONArray(data.cols.col);

	for (var i = 0; i < lstCols.length; i++) {
		col = lstCols[i];
		hc = document.createElement("COL");
		processCSS(hc, col);
		hc.style.width = col["@attributes"].width;
		al= col["@attributes"].align;
		if (al != null && al!="") hc.align = al;
		al= col["@attributes"].valign;
		if (al != null && al!="") hc.vAlign = al;
		gc.appendChild(hc);
	}

	//create rows of the layout table
	var hr, r, lstRow = Common.getJSONArray(data.rows.row);
	var hc,lstCell;

	for (var i = 0; i < lstRow.length; i++) {
		r= lstRow[i];
		hr = tbl.insertRow(-1);
		processCSS(hr,r);
		hr.style.height = r["@attributes"].height;
		al = r["@attributes"].align;
		if (al != null && al != "")
			hr.align=al;
		al = r["@attributes"].valign;
		if (al != null && al != "")
			hr.vAlign=al;
		lstCell = Common.getJSONArray(r.cell);
		for (var j = 0; j < lstCell.length; j++) {
			c=lstCell[j];
			hc = hr.insertCell(-1);
			processTD(hc, c);
		}
	}
}

/*  */
function processTD(htmCell, xmlCell) {
	processCSS(htmCell, xmlCell);
	var rowspan = xmlCell["@attributes"].rowspan;
	var colspan = xmlCell["@attributes"].colspan;
	if (null != rowspan)
		htmCell.rowSpan = rowspan;
	if (null != colspan)
		htmCell.colSpan = colspan;
	al = xmlCell["@attributes"].align;
	if (al != null && al!="") htmCell.align = al;
	al = xmlCell["@attributes"].valign;
	if (al != null && al!="") htmCell.vAlign = al;

	var data = xmlCell.layout;
	if (null != data) {
		var tbl = document.createElement("TABLE");
		processLayout(data, tbl);
		htmCell.appendChild(tbl);
	} else if ((data = xmlCell.image) != null) {
		processImage(htmCell, data);
	} else {
		htmCell[HW_DATA_CONTROL] = xmlCell;
		if (g_readonly=="false" || g_readonly == false ) {
			var lst = Common.getJSONArray(xmlCell.d);
			for (var i = 0; i < lst.length; i++) {
				if (lst[i]["@attributes"] && lst[i]["@attributes"].id)
					g_oEditorContainer.add(lst[i]["@attributes"].id, htmCell, lst[i]);
			}
		}
		updateHTMLCell(htmCell);
	}

	//set link object
	var link = xmlCell["@attributes"].link;
	processLink(link,htmCell);
}

/* update the html cell according to the contained xml node */
function updateHTMLCell(htmCell) {
	$(htmCell).empty();
	var oData = htmCell[HW_DATA_CONTROL];
	var value = "";
	if (oData["#text"]) {
		value = oData["#text"];
	} else if (oData.d) {
		if (oData.d["#text"]) value = oData.d["#text"];
	}
	$(htmCell).append(value);
}

/* set the inline css style and class of htm object according to the xml data*/
function processCSS(htmObj, data) {
	if (!data["@attributes"]) {
		return;
	}
	var attr = data["@attributes"]["class"];
	if (attr!=null && attr!="")
		htmObj.className = attr;
	attr = data["@attributes"].style;
	if (attr!=null && attr!="")
		setCSS(htmObj, attr);
}

/* set the attributes of htm object according to the xml data*/
function processAttributes(htmObj, data) {
	if (!data["@attributes"]) return;
	var oAttr = data["@attributes"];
	var attr = oAttr.border;
	if (attr!=null && attr!="") htmObj.border = parseInt(attr);
	attr = oAttr.cellpadding;
	if (attr!=null && attr!="") htmObj.cellPadding = parseInt(attr);
	attr = oAttr.cellspacing;
	if (attr!=null && attr!="") htmObj.cellSpacing = parseInt(attr);
	attr = oAttr.bordercolor;
	if (attr!=null && attr!="") htmObj.borderColor = attr;
	attr = oAttr.bgcolor;
	if (attr!=null && attr!="") htmObj.bgColor = attr;
	attr = oAttr.background;
	if (attr!=null && attr!="") htmObj.background = attr;
}

/* set the inline css style attribute of a htm object*/
function setCSS(htmObj, cs){
	var c = WinManager.parseStyle(cs);
	for (o in c)
		eval("htmObj.style."+o+"=\""+c[o]+"\"");
}

function processLink(link, htmCell) {
	if (link != null) {
		var params = new Array();
		params[0] = WinManager.parseStyle(link);	//params are object format,like params[paramName] = paramValue;
		params[0].sessionId = g_cid;
		params[1] = parseStyleToArray(link);		//params are Array format, like params [i][0] = paramName, params [0][1] = paramValue;
		
		if (params[0].linkVisible!="false") {
			htmCell.style.cursor = "pointer";
			htmCell.style.color = "blue";
			var sColor = params[0].linkColor;
			if (sColor != null && sColor != "")
				htmCell.bgColor = sColor;
				
			var sTextDecoration = params[0].textDecoration;
			if (sTextDecoration != null && sTextDecoration != "")
				htmCell.style.textDecoration = sTextDecoration;
			
			var sLinkMouseOver = params[0].linkMouseOver;
			if (sLinkMouseOver)
				htmCell.setAttribute(HW_LINK_MOUSE_OVER,sLinkMouseOver);
			htmCell.onmouseover = mouseOver;
			
			var sLinkMouseOut = params[0].linkMouseOut;
			if (sLinkMouseOut)
				htmCell.setAttribute(HW_LINK_MOUSE_OUT,sLinkMouseOut);
			htmCell.onmouseout = mouseOut;	
			
			htmCell[HW_LINK] = 	params;
			htmCell.onclick = OnLinkClicked;
		}
	}
}

function OnLinkClicked() {
	var sender = event.srcElement;
	var link = sender[HW_LINK];
	if (link[0].linkCall==null|| link[0].linkCall=="")
		return;
	eval(link[0].linkCall+"(link[0], link[1])");
}


function processImage(htmCell, data) {
	var img = document.createElement("IMG");
	htmCell.appendChild(img);
	img.src = data["#text"];

	//set link object
	var link = data["@attributes"].link;
	processLink(link, img);
}

function buildDevice(rt, xmlDev) {
	var oAttribute = xmlDev["@attributes"];
	var mx = oAttribute.metrix;
	var w = oAttribute.width;
	var h = oAttribute.height;
	w = parseInt(w);
	h = parseInt(h);
	$(rt).css("height",h);
}

//* build and set the style sheet in the html */
function buildStyles(xmlStyles) {
	var sty, lst = xmlStyles.style;
	if (!lst) return;
	if (lst && typeof(lst.length) == "undefined") {
		var style = lst;
		lst = new Array();
		lst.push(style);
	}

	for (var i = 0; i < lst.length; i++) {
		sty = lst[i];
		var sPrefix = parseStylePrefix(sty.tar);
		var v = sty.val;
		if (null != v && "" != v)
			if (window.ActiveXObject){
				var oStyleSheet = document.createStyleSheet();
				oStyleSheet.addRule(sPrefix, v);
			}else{
//				var index= oStyleSheet.cssRules.length; 
				document.styleSheets[0].insertRule(sPrefix+"{"+v+"}"); 
			}
	}
}

function buildScripts(xmlScripts) {
	var s, st = xmlScripts.script;
	if (!st) return;
	if (st && typeof(st.length) == "undefined") {
		var scrpit = st;
		st = new Array();
		st.push(scrpit);
	}
	var sc;
	var head = document.getElementsByTagName('head').item(0);
	
	for (var i = 0; i < st.length; i++) {
		sc = document.createElement("SCRIPT");
		s = st[i];
		if(s.getAttribute("src") == null) {
			sc.text = s.text;	
		} else {
			sc.src= s.getAttribute("src");	
		}		
		head.appendChild(sc);
	}
}

//* parse the prefix of the rule in the style sheet */
function parseStylePrefix(sTar) {
	var sPrefix;
	var arr = sTar.split(".");
	if (3 != arr.length)
		return;
	switch (arr[1]) {
		case "table":
			sPrefix = "TABLE."; break;
		case "row":
			sPrefix = "TR."; break;
		case "cell":
			sPrefix = "TD."; break;
		case "input":
			sPrefix = "INPUT."; break;
		default:
			sPrefix = arr[1] + "."; break;
	}
	return sPrefix + arr[2];
}

function mouseOver() {
	var sMouseOver = event.srcElement.getAttribute(HW_LINK_MOUSE_OVER); 
	if (sMouseOver != null && sMouseOver != "") {
		if(sMouseOver.indexOf("(") < 0) {
			event.srcElement.style.color = sMouseOver;
		} else {
			eval(sMouseOver);
		}
	}else {
		event.srcElement.style.textDecoration = "underline";	
	}
}

function mouseOut() {
	var sMouseOver = event.srcElement.getAttribute(HW_LINK_MOUSE_OUT); 
	if (sMouseOver != null && sMouseOver != "") {
		if(sMouseOver.indexOf("(") < 0) {
			event.srcElement.style.color = sMouseOver;
		} else {
			eval(sMouseOver);
		}
	}else {
		event.srcElement.style.textDecoration = "";
	}
}

function parseStyleToArray(sStyle) {
	var aStyle = sStyle.split(";");
	var oStyle = new Array();
	var attstr, aCtrlAttrs = new Array();
	for (var i = 0; i< aStyle.length; i++) {
		attstr = aStyle[i].split(":");
		if (attstr[0] == "" || attstr[1] == null) continue;
		var an = attstr[0].trim().split("-");
		var n = an[0];
		for (var j=1 ; j<an.length; j++)
			n += an[j].charAt(0).toUpperCase()+an[j].substring(1);
		oStyle[oStyle.length] = new Array();
		oStyle[oStyle.length - 1][0] = n;
		oStyle[oStyle.length - 1][1] = attstr[1].trim();
	}
	return oStyle;
}

function loadImg(imgSrc) {
	window.event.srcElement.src = imgSrc;
}